package web;

import cn.hutool.core.bean.BeanUtil;
import com.nf.mvc.ViewResult;
import com.nf.mvc.file.MultipartFile;
import com.nf.mvc.argument.RequestBody;
import com.nf.mvc.mapping.RequestMapping;
import com.nf.mvc.view.FileViewResult;
import com.nf.mvc.view.PlainViewResult;
import com.nf.mvc.vo.ResponseVO;
import entity.Product;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import java.io.IOException;

import static com.nf.mvc.handler.HandlerHelper.*;

public class ProductController {

    @RequestMapping("/list")
    public ViewResult list(HttpServletRequest request) {
        //list?p1="f1"&a=1&b
        // request.getPart("f1")
        //part.write("asdfasd");
        Product bean = BeanUtil.toBean(request.getParameterMap(), Product.class);
        return plain("list...");

    }

    @RequestMapping("/list2")
    public ViewResult list2(HttpServletRequest request, HttpServletResponse response) {
        return plain("list2...");
    }

    @RequestMapping("/list3")
    public ViewResult list3(HttpServletRequest request, HttpServletResponse response, HttpSession session) {

        return plain("list2...");
    }


    @RequestMapping("/list4")
    public ViewResult list4(int a, Double b) {

        return plain("list4..." + a + " b: " + b);
    }


    @RequestMapping("/list5")
    public ViewResult list5(@RequestBody Product product) {

        System.out.println(product);
        return plain("list5..." + product);
    }

    @RequestMapping("/list6")
    public ViewResult list6(Part part) {

        try {
            part.write("d:/tmp/" + part.getSubmittedFileName());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return plain("list5...upload ok");
    }


    @RequestMapping("/list7")
    public ViewResult list7(MultipartFile multipartFile) {

        try {
            multipartFile.transferTo("d:/tmp/" + multipartFile.getOriginalFilename());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return plain("list6...upload ok");
    }

    @RequestMapping("/list8")
    public ViewResult list8(String filename) {

        String realPath = "d:/tmp/" + filename;
        // return new FileViewResult(realPath);
        return file(realPath);
    }


    @RequestMapping("/list9")
    public ViewResult list9(Product product) {
        return json(product);
    }


    @RequestMapping("/ex1")
    public ViewResult ex1(int a, int b) {
        int result = a / b;
        return json(new ResponseVO(200, result + ""));
    }
}
